package com.example.userlogincenter.userCenter.service.impl;

import cn.hutool.core.util.RandomUtil;

import cn.hutool.json.JSONUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.userlogincenter.userCenter.entity.CenterUser;
import com.example.userlogincenter.userCenter.mapper.CenterUserMapper;
import com.example.userlogincenter.userCenter.pojo.RoleVo;
import com.example.userlogincenter.userCenter.pojo.tokenUser;
import com.example.userlogincenter.userCenter.pojo.userRegisterVo;
import com.example.userlogincenter.userCenter.service.ICenterUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.userlogincenter.userCenter.util.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import static com.example.userlogincenter.userCenter.util.randomUtils.randomAccess;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Tangshen
 * @since 2022-11-02
 */
@Service
public class CenterUserServiceImpl extends ServiceImpl<CenterUserMapper, CenterUser> implements ICenterUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    /*
    * 保存用户
    * */
    @Override
    public boolean saveUser(userRegisterVo registerUser) throws UnsupportedEncodingException {

        //判断是否存在该用户
        QueryWrapper<CenterUser> queryWrapper = new QueryWrapper<>();
        QueryWrapper<CenterUser> phonenumberWrapper = queryWrapper.eq("phonenumber", registerUser.getPhonenumber());
        long count = this.count(phonenumberWrapper);
        if (count != 0){
            throw new RuntimeException("用户已存在..");
        }else {
            String salt = randomAccess();
            String encrypValue = encrypUtils.encrypValue(registerUser.getUserpassword(),salt);
            registerUser.setUserpassword(encrypValue);
            registerUser.setSalt(salt);
            CenterUser user = new CenterUser();
            BeanUtils.copyProperties(registerUser,user);
            boolean save = this.save(user);
            if (save){
                return true;
            }
            return false;
        }
    }

    /**
     *
     *
     * */
    @Override
    public tokenUser findUser(String phonenumber) {
        //获取该用户
         QueryWrapper<CenterUser> queryWrapper = new QueryWrapper<>();
         queryWrapper.eq("phonenumber", phonenumber).select();
         CenterUser user = this.getOne(queryWrapper);
         tokenUser tokenUser = new tokenUser();
         tokenUser.setUserId(user.getUserid());
         tokenUser.setNickname(user.getNickname());
         tokenUser.setUserphone(user.getPhonenumber().substring(user.getPhonenumber().length()-4,user.getPhonenumber().length()-1));
        //赋值到tokenUser
        return tokenUser;
    }

    /**
     *
     * 根据手机号查询用户
     *
     * */
    @Override
    public CenterUser getOneByPhone(String phonenumber) {
        QueryWrapper<CenterUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phonenumber",phonenumber);
        CenterUser user = this.getOne(queryWrapper);
        return user;
    }

    @Override
    public RoleVo getRoleByUserId(Long roleId) {

        return null;
    }

    @Override
    public CenterUser getUserById(Long id) {
        CenterUser centerUser = this.baseMapper.selectById(id);
        return centerUser;
    }

    @Override
    public boolean getVerificationCode(String phoneNumber) throws Exception {
        HashMap<String,String> verificationCode = new HashMap<>();
        String code = RandomUtil.randomNumbers(6);
        verificationCode.put("code",code);
        //将注册验证码存入到redis,有效时长为120秒
        redisTemplate.opsForValue().set("RverificationCode",code,120, TimeUnit.SECONDS);
        String codeJson = JSONUtil.toJsonStr(verificationCode);
        Client client = aliyunUtils.createClient();
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest();
       sendSmsRequest.setPhoneNumbers(phoneNumber);
       sendSmsRequest.setTemplateCode("SMS_154950909");
       sendSmsRequest.setSignName("SignName");
       sendSmsRequest.setTemplateParam(codeJson);

        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            Integer statusCode = sendSmsResponse.getStatusCode();
            if (statusCode == 200){
                return true;
            }
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return false;
    }


}
